package com.idanchuang.component.shadow.route;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.idanchuang.component.mybatis.plus.ComponentMybatisPlusPureAutoConfiguration;
import com.idanchuang.component.shadow.route.common.aop.ShadowRouteDataSourceAspect;
import com.idanchuang.component.shadow.route.common.conf.ShadowRouteDataSourceProperties;
import com.idanchuang.component.shadow.route.common.conf.ShadowRouteProperties;
import com.idanchuang.component.shadow.route.common.dynamic.ShadowRoutingDataSource;
import com.idanchuang.component.shadow.route.common.filter.ShadowRouteDataSourceFilter;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Shadow Route Auto Configuration
 *
 * @author Raistlin
 */
@ConditionalOnProperty(prefix = "idanchuang.component.shadow.route", name = "enabled", havingValue = "true")
@AutoConfigureAfter(value = {ComponentMybatisPlusPureAutoConfiguration.class})
@AutoConfigureBefore(value = {DataSourceAutoConfiguration.class})
@Configuration
public class ComponentShadowRouteAutoConfiguration {

    private final Logger logger = LoggerFactory.getLogger(ComponentShadowRouteAutoConfiguration.class.getName());

    @Bean
    @ConfigurationProperties(prefix = "idanchuang.component.shadow.route")
    public ShadowRouteProperties shadowRouteProperties() {
        return new ShadowRouteProperties();
    }

    @Bean
    public ShadowRouteDataSourceFilter shadowRouteDataSourceFilter(ShadowRouteProperties shadowRouteProperties) {
        return new ShadowRouteDataSourceFilter(shadowRouteProperties);
    }

    @Bean
    @ConditionalOnMissingBean(ShadowRouteDataSourceFilter.class)
    public ShadowRouteDataSourceAspect shadowRouteDataSourceAspect(ShadowRouteProperties shadowRouteProperties) {
        return new ShadowRouteDataSourceAspect(shadowRouteProperties);
    }

    @ConfigurationProperties(prefix = "idanchuang.datasource")
    @Bean
    public ShadowRouteDataSourceProperties shadowRouteDataSourceProperties() {
        return new ShadowRouteDataSourceProperties();
    }

    @Bean
    public DataSource actualDataSource(ShadowRouteDataSourceProperties properties) {
        return DataSourceBuilder.create(properties.getClassLoader())
                .type(properties.getActual().getType())
                .driverClassName(properties.getActual().getDriverClassName())
                .url(properties.getActual().getUrl())
                .username(properties.getActual().getUsername())
                .password(properties.getActual().getPassword())
                .build();
    }

    @Bean
    public DataSource shadowDataSource(ShadowRouteDataSourceProperties properties) {
        return DataSourceBuilder.create(properties.getClassLoader())
                .type(properties.getShadow().getType())
                .driverClassName(properties.getShadow().getDriverClassName())
                .url(properties.getShadow().getUrl())
                .username(properties.getShadow().getUsername())
                .password(properties.getShadow().getPassword())
                .build();
    }

    @Bean
    @Primary
    public DataSource dynamicDataSource(ShadowRouteProperties properties,
                                        @Qualifier("actualDataSource") DataSource actualDataSource,
                                        @Qualifier("shadowDataSource") DataSource shadowDataSource) {
        ShadowRoutingDataSource dynamicDataSource = new ShadowRoutingDataSource();
        Map<Object, Object> dataSources = new HashMap<>();
        dataSources.put(properties.getActualDataSourceName(), actualDataSource);
        dataSources.put(properties.getShadowDataSourceName(), shadowDataSource);
        dynamicDataSource.setTargetDataSources(dataSources);
        return dynamicDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource, Interceptor... plugins) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        sqlSessionFactoryBean.setPlugins(plugins);
        return sqlSessionFactoryBean.getObject();
    }

}
